package com.dongliu.controller;

import com.dongliu.domain.User;
import com.dongliu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PutMapping
    public Result updateById(@RequestBody User user) {
        boolean flag = userService.updateById(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR, flag);
    }

    @GetMapping("/{username}")
    public Result getByUsername(@PathVariable String username) {
        User user = userService.getByUsername(username);
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "" : "数据查询失败，请重试！";
        return new Result(code, user, msg);
    }

    @PutMapping("/register")
    public Result save(@RequestBody User user) {
        User user1 = userService.getByUsername(user.getUsername());
        if(user1 != null){
            return new Result(Code.REPEAT_ERR, 0);
        }
        user.setLimitNumber(10);
        user.setLentNumber(0);
        boolean flag = userService.save(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR, flag);
    }
}
